#include "../libxluploader.h"
#include "sites.h"
#include <assert.h>
#include <iostream>

/************************************************************************
 response:
 ...
 <tr><td nowrap="nowrap">Hotlink</td>
 <td class="link"><input type="text" readonly="readonly" onclick="javascript:this.focus(); this.select();" size="50" value="http://i.imagehost.org/0644/250px-Huizong.jpg" /></td>
 </tr>
 ...

 we will extract:
 http://i.imagehost.org/0644/250px-Huizong.jpg

 ************************************************************************/

std::string CSiteImageHostOrg::parseImageUrl (const std::string &response) {
	if (!m_pcreCodePic) {
		return "";
	}

	std::string url;

	const int size = 30;
	int ov[size] = {0};
	file_put_contentsA("d:\\imagehost.txt", response);
	const char *text = response.c_str();
	int res = pcre_exec(m_pcreCodePic, NULL, text, response.length(), 0, 0, ov, size);
	if (res != 2) {
		return "";
	}
	url = response.substr(ov[2], ov[3] - ov[2]);


	return url;
}

std::string CSiteImageHostOrg::getUrl() const {
	return "http://imagehost.org/";
}

void CSiteImageHostOrg::prePost(const std::string &html, const HtmlDom &dom, std::string &cookie) const {
	HtmlNodeIterArray imgs = html_get_nodes_by_tag(dom, "img");
	for (HtmlNodeIterArray::iterator it = imgs.begin(); it != imgs.end(); ++ it) {
		(*it)->parseAttributes();
		std::string src = (*it)->attribute("src").second;
		const char *p = src.c_str();
#if 1
		if (strstr(p, "/?p=verify&amp;") == p) {
			// found the url
			src = "http://imagehost.org" + src;

			size_t offset;
			while ((offset = src.find("&amp;")) != std::string::npos) {
				src.erase(offset + 1, 4);
			}
			
			std::string dummy;
			http_get(dummy, src.c_str(), cookie, NULL, NULL, getUrl());
			break;
		}
#else
		if (p[0] == '/') {
			src = "http://imagehost.org" + src;
		}
		std::string dummy;
		http_get(dummy, src.c_str(), cookie, NULL, NULL, getUrl());
#endif
	}
}


CSiteImageHostOrg::CSiteImageHostOrg () {
	m_errPic = NULL;

	//  http://i.imagehost.org/0644/250px-Huizong.jpg
	const char *pattern_pic = "value=\"(http://.\\.imagehost\\.org/\\d+/[^\"]+)\"";
	int flags = PCRE_BSR_ANYCRLF | PCRE_UTF8 | PCRE_MULTILINE | PCRE_DOTALL;
	m_pcreCodePic = pcre_compile(pattern_pic, flags, &m_errPic, &m_errPicOffset, NULL);
}

CSiteImageHostOrg::~CSiteImageHostOrg() {
	if (m_pcreCodePic) {
		pcre_free(m_pcreCodePic);
	}
}

TCHAR* CSiteImageHostOrg::getSiteName () {
	return _T("ImageHost.org");
}

#ifdef DEBUG_SIZE_IMAGEHOST_ORG
ISite* debugGetSite() {
	static CSiteImageHostOrg tp;
	return &tp;
}
#endif

